package org.springblade.modules.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.ElevatorPrincipalSaveDTO;
import org.springblade.modules.admin.entity.MaintainBusinessLog;
import org.springblade.modules.admin.enums.MaintainBusinessLogEnum;
import org.springblade.modules.admin.service.MaintainBusinessLogService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springblade.modules.admin.mapper.ElevatorPrincipalDeptMapper;
import org.springblade.modules.admin.entity.ElevatorPrincipalDept;
import org.springblade.modules.admin.service.ElevatorPrincipalDeptService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ElevatorPrincipalDeptServiceImpl extends BaseServiceImpl<ElevatorPrincipalDeptMapper, ElevatorPrincipalDept> implements ElevatorPrincipalDeptService{

	@Autowired
	private MaintainBusinessLogService businessLogService;
	@Autowired
	private IDeptService deptService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean savePrincipalDept(ElevatorPrincipalSaveDTO saveDTO) {

		if(ObjectUtil.isEmpty(saveDTO.getElevatorIds())){
			throw new ServiceException("电梯ID不可为空");
		}

		List<ElevatorPrincipalDept> newPrincipalDeptList = new ArrayList<>();
		List<ElevatorPrincipalDept> oldPrincipalDeptList = super.list(Wrappers.<ElevatorPrincipalDept>lambdaQuery().eq(ElevatorPrincipalDept::getType,saveDTO.getType()).in(ElevatorPrincipalDept::getElevatorId,saveDTO.getElevatorIds()));
		// 责任组id为空时
		if(ObjectUtil.isEmpty(saveDTO.getPrincipalDeptList())){
			// 历史关联不为空时 获取历史关联电梯
			if(ObjectUtil.isNotEmpty(oldPrincipalDeptList)){
				saveDTO.getElevatorIds().forEach(e -> {
					ElevatorPrincipalDept principalDept = oldPrincipalDeptList.stream().filter(k -> k.getElevatorId().equals(e) && k.getType().equals(saveDTO.getType())).findAny().orElse(null);
					if(ObjectUtil.isNotEmpty(principalDept)){
						principalDept.setElevatorId(e);
						principalDept.setType(saveDTO.getType());
						principalDept.setDeptId(null);
						newPrincipalDeptList.add(principalDept);
					}
				});
			}
			// 插入历史关联电梯解除关联日志及解除关联
			if(ObjectUtil.isNotEmpty(newPrincipalDeptList)){
				return this.saveElevatorPrincipalDeptLog(newPrincipalDeptList) && super.saveOrUpdateBatch(newPrincipalDeptList);
			}else {
				return Boolean.TRUE;
			}
		}
		// 责任组id不为空时
		// 获取部门祖级名称
		saveDTO.getPrincipalDeptList().forEach(e -> {
			String deptIds = e.getAncestors()+","+e.getId();
			List<String> deptNames = deptService.getDeptNames(deptIds);
			e.setAncestorNames(String.join("/",deptNames));
		});
		// 历史关联电梯为空
		if(ObjectUtil.isEmpty(oldPrincipalDeptList)){
			saveDTO.getElevatorIds().forEach(e -> saveDTO.getPrincipalDeptList().forEach(j -> {
				ElevatorPrincipalDept principalDept = new ElevatorPrincipalDept();
				principalDept.setElevatorId(e);
				principalDept.setDeptId(j.getId());
				principalDept.setDeptName(j.getAncestorNames());
				principalDept.setType(saveDTO.getType());
				newPrincipalDeptList.add(principalDept);
			}));
		}else {
			// 历史关联电梯不为空时
			saveDTO.getElevatorIds().forEach(e -> saveDTO.getPrincipalDeptList().forEach(j -> {
				ElevatorPrincipalDept principalDept = oldPrincipalDeptList.stream().filter(k -> k.getElevatorId().equals(e) && k.getType().equals(saveDTO.getType())).findAny().orElse(null);
				// 当前电梯不存在历史关联 新增关联
				if(ObjectUtil.isEmpty(principalDept)){
					principalDept = new ElevatorPrincipalDept();
					principalDept.setElevatorId(e);
					principalDept.setDeptId(j.getId());
					principalDept.setDeptName(j.getAncestorNames());
					principalDept.setType(saveDTO.getType());
					newPrincipalDeptList.add(principalDept);
				}else {
					// 当前电梯存在历史关联 修改关联
					if(!j.getId().equals(principalDept.getDeptId())){
						principalDept.setDeptId(j.getId());
						principalDept.setDeptName(j.getAncestorNames());
						newPrincipalDeptList.add(principalDept);
					}
				}
			}));

//			Map<Long,List<ElevatorPrincipalDept>> elevatorGroup = oldPrincipalDeptList.stream().collect(Collectors.groupingBy(ElevatorPrincipalDept::getElevatorId));
//			saveDTO.getElevatorIds().forEach(e -> {
//				List<ElevatorPrincipalDept> principalDeptList = elevatorGroup.get(e);
//
//			});
		}
		if(ObjectUtil.isNotEmpty(newPrincipalDeptList)){
			return this.saveElevatorPrincipalDeptLog(newPrincipalDeptList) && super.saveOrUpdateBatch(newPrincipalDeptList);
		}else {
			return Boolean.TRUE;
		}
	}

	@Override
	public List<ElevatorPrincipalDept> listAll() {
		return baseMapper.listAll();
	}

	@Override
	public String getPrincipalDeptNames(Long elevatorId) {
		return baseMapper.getPrincipalDeptNames(elevatorId);
	}

	@Override
	public String getPrincipalUseNames(Long elevatorId) {
		return baseMapper.getPrincipalUserNames(elevatorId);
	}

	@Override
	public List<ElevatorPrincipalDept> listInMaintainElevatorByDeptIds(List<Long> deptIds) {
		return baseMapper.listInMaintainElevatorByDeptIds(deptIds);
	}

	@Override
	public List<ElevatorPrincipalDept> selectDeptGroupByElevatorIds(List<Long> elevatorIds) {
		return baseMapper.selectDeptGroupByElevatorIds(elevatorIds);
	}

	@Override
	public List<ElevatorPrincipalDept> listElevatorDeptByElevatorIds(List<Long> elevatorIds) {
		return baseMapper.listElevatorDeptByElevatorIds(elevatorIds);
	}

	/**
	 * 电梯负责人更新日志
	 * @param newPrincipalDeptList
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveElevatorPrincipalDeptLog(List<ElevatorPrincipalDept> newPrincipalDeptList) {
		if(ObjectUtil.isEmpty(newPrincipalDeptList)){
			return Boolean.TRUE;
		}
		List<Long> elevatorIds = newPrincipalDeptList.stream().map(ElevatorPrincipalDept::getElevatorId).collect(Collectors.toList());
		List<MaintainBusinessLog> businessLogList = businessLogService.listNewestGroupByElevator(elevatorIds,MaintainBusinessLogEnum.ELEVATOR_MAINTAIN_PRINCIPAL_DEPT_UPDATE.getType());
		List<MaintainBusinessLog> saveList = new ArrayList<>();
		newPrincipalDeptList.forEach(e -> {
			// 当前电梯不存在历史修改记录 新增修改记录
			if(ObjectUtil.isEmpty(businessLogList)){
				MaintainBusinessLog newLog = new MaintainBusinessLog();
				newLog.setParamKey(e.getElevatorId());
				newLog.setType(MaintainBusinessLogEnum.ELEVATOR_MAINTAIN_PRINCIPAL_DEPT_UPDATE.getType());
				JSONObject oldContent = new JSONObject();
				oldContent.put("names","未设置");
				newLog.setOldContent(oldContent);
				JSONObject newContent = new JSONObject();
				newContent.put("ids",String.valueOf(e.getDeptId()));
				newContent.put("names",e.getDeptName());
				newLog.setNewContent(newContent);
				saveList.add(newLog);
			}else {
				MaintainBusinessLog businessLog = businessLogList.stream().filter(j -> j.getParamKey().equals(e.getElevatorId())).findAny().orElse(null);
				MaintainBusinessLog newLog = new MaintainBusinessLog();
				// 当前电梯不存在历史记录 插入分组记录
				if(ObjectUtil.isEmpty(businessLog)){
					newLog.setParamKey(e.getElevatorId());
					newLog.setType(MaintainBusinessLogEnum.ELEVATOR_MAINTAIN_PRINCIPAL_DEPT_UPDATE.getType());
					JSONObject oldContent = new JSONObject();
					oldContent.put("names","未设置");
					newLog.setOldContent(oldContent);
					JSONObject newContent = new JSONObject();
					newContent.put("ids",String.valueOf(e.getDeptId()));
					newContent.put("names",e.getDeptName());
					newLog.setNewContent(newContent);
					saveList.add(newLog);
				}else {
					// 当前电梯存在历史记录
					// 当前最新为删除 插入未设置记录
					if(ObjectUtil.isEmpty(e.getDeptId())){
						newLog.setParamKey(e.getElevatorId());
						newLog.setType(MaintainBusinessLogEnum.ELEVATOR_MAINTAIN_PRINCIPAL_DEPT_UPDATE.getType());
						JSONObject oldContent = new JSONObject();
						oldContent.put("ids",businessLog.getNewContent().getString("ids"));
						oldContent.put("names",businessLog.getNewContent().getString("names"));
						newLog.setOldContent(oldContent);
						JSONObject newContent = new JSONObject();
						newContent.put("names","未设置");
						newLog.setNewContent(newContent);
						saveList.add(newLog);
					}else {
						// 当前最新为修改 插入更新记录
						newLog.setParamKey(e.getElevatorId());
						newLog.setType(MaintainBusinessLogEnum.ELEVATOR_MAINTAIN_PRINCIPAL_DEPT_UPDATE.getType());
						if(ObjectUtil.isEmpty(businessLog.getNewContent().getString("ids"))){
							JSONObject oldContent = new JSONObject();
							oldContent.put("names",businessLog.getNewContent().getString("names"));
							newLog.setOldContent(oldContent);
						}else {
							JSONObject oldContent = new JSONObject();
							oldContent.put("ids",businessLog.getNewContent().getString("ids"));
							oldContent.put("names",businessLog.getNewContent().getString("names"));
							newLog.setOldContent(oldContent);
						}
						JSONObject newContent = new JSONObject();
						newContent.put("ids",String.valueOf(e.getDeptId()));
						newContent.put("names",e.getDeptName());
						newLog.setNewContent(newContent);
						saveList.add(newLog);
					}
				}
			}
		});

		return businessLogService.saveBatch(saveList);
	}
}
